package pt.uminho.di.poo.transitarios.gestao;

import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;

public abstract class AbstractGestaoGenerica<T extends IElementoGenerico<?>>
		implements IGestaoGenerica<T> {

	private static final long serialVersionUID = 1L;

	protected TreeMap<String, T> map;

	public AbstractGestaoGenerica() {
		this.map = new TreeMap<String, T>();
	}

	@Override
	public void adicionar(T p) {
		if (p != null) {
			this.map.put(p.getCodigo(), p);
		}
	}

	@Override
	public T devolve(String codigo) {

		if (codigo == null) {
			return null;
		} else {
			return this.map.get(codigo);
		}
	}

	@Override
	public Collection<T> devolveTodos() {
		return this.map.values();
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (this.getClass() != obj.getClass()) {
			return false;
		}
		final AbstractGestaoGenerica<T> other = (AbstractGestaoGenerica<T>) obj;
		if (this.map == null) {
			if (other.map != null) {
				return false;
			}
		} else if (!this.map.equals(other.map)) {
			return false;
		}
		return true;
	}

	@Override
	public boolean existe(String codigo) {
		if (codigo == null) {
			return false;
		} else {
			return this.map.containsKey(codigo);
		}
	}

	@Override
	public boolean existe(T p) {
		if (p == null) {
			return false;
		} else {
			return this.map.containsKey(p.getCodigo());
		}
	}

	@Override
	public Iterator<T> iterator() {
		return this.map.values().iterator();
	}

	@Override
	public void remover(String codigo) {
		this.map.remove(codigo);

	}

	@Override
	public void remover(T p) {
		if (p != null) {
			this.map.remove(p.getCodigo());
		}

	}

	@Override
	public int size() {
		return this.map.size();
	}

}